package pro.shuangxi.model.book.pojo;

import org.springframework.beans.factory.annotation.Autowired;
import pro.shuangxi.model.book.helper.thread.ThreadPool;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @author ：mengshx
 * @date ：Created in 2020/11/29 10:37
 * @description：小说实体
 */
public class Story {


    @Autowired
    private static ExecutorService threadPool = ThreadPool.pool;
    private String name;
    private BufferedReader bufferedReader;
    private ArrayList<String> content = new ArrayList<>(1024000);
    private int nowPage=1;
    private Date time=new Date();
    private boolean isReady=false;
    private Future<Boolean> submit;



    public Story(String name){
        System.out.println(threadPool);
        try {
            InputStream stream = new FileInputStream(new File(name));
            InputStreamReader reader = null;
            reader = new InputStreamReader(stream,"utf-8");
            bufferedReader = new BufferedReader(reader);
            String s = bufferedReader.readLine();
             submit = threadPool.submit(new Callable<Boolean>() {

                @Override
                public Boolean call() throws Exception {
                    String temp = "";
                    try {
                        while ((temp = bufferedReader.readLine()) != null) {
                            content.add(temp);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                    }

                    return true;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("读取失败");
        }


    }

    public String readPage(int pageNum) {
        if (!isReady) {
            try {
                Boolean isOk = submit.get();
                if (isOk) {
                    isReady=true;
                }else {
                    return "小说初始化好像出现问题了";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String temp = "<p>";
        int from = (pageNum - 1) * 100;
        int to = pageNum * 100;
        for (; from < to&&from <content.size(); from++) {
            temp = temp + content.get(from)+"<br/>";
        }
        temp = temp + "</p>";
        time=new Date();
        return temp;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



    public int getNowPage() {
        return nowPage;
    }

    public void setNowPage(int nowPage) {
        this.nowPage = nowPage;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }
}
